package com.nk.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nk.domain.*;
import com.nk.mapper.EmployeeMapper;
import com.nk.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public PageListRes getEmployeeList(QueryVo vo) {

        //设置分页
        Page<Object> page = PageHelper.startPage(vo.getPage(), vo.getRows());
        List<Employee> employeeList = employeeMapper.selectAll(vo);
        PageListRes employeeListRes = new PageListRes();
        employeeListRes.setTotal(page.getTotal());
        employeeListRes.setRows(employeeList);
        return employeeListRes;
    }

    @Override
    public void saveEmployee(Employee employee) {

        employeeMapper.insert(employee);

        for (Role role : employee.getRoleList()) {
            employeeMapper.insertEmployeeAndRole(employee.getId(),role.getRid());
        }
    }

    @Override
    public void updateEmployee(Employee employee) {

        // 打破角色和用户的关系
        employeeMapper.deleteRoleById(employee.getId());
        for (Role role : employee.getRoleList()) {
            employeeMapper.insertEmployeeAndRole(employee.getId(),role.getRid());
        }
        employeeMapper.updateByPrimaryKey(employee);
    }

    @Override
    public void employeeUpdateState(long id) {
        employeeMapper.updateStateByKey(id);
    }

    @Override
    public Employee getEmployeeByName(String username) {

        Employee employee = employeeMapper.selectByName(username);
        return employee;
    }

    @Override
    public List<String> getRoleNameByEid(Long id) {
        List<String> roleNames = employeeMapper.getRoleNameByEid(id);
        return roleNames;
    }

    @Override
    public List<String> getPermissionByEid(Long id) {
        List<String> permissionList = employeeMapper.getPermissionByEid(id);
        return permissionList;
    }

}
